<template>
    <div class="article-page">
        <span class="article-title">文章管理</span>
        <div class="fliter">
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width:60px;">文章ID：</span>
                <el-input v-model="articleId" style="width: 200px;" placeholder="请输入文章ID" clearable />
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">文章分类：</span>
                <el-cascader style="width: 200px;" clearable v-model="categoryId" :options="options" filterable
                    :props="categoryProps" placeholder="请选择文章分类" />
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">账户名称：</span>
                <el-select v-model="accountId" placeholder="请选择账户名称" style="width: 200px;" clearable
                    @change="handleSelectAccount">
                    <el-option v-for="item in accountNameOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">所属网站：</span>
                <el-select v-model="siteId" style="width: 200px;" placeholder="请选择所属网站" clearable filterable>
                    <el-option v-for="item in siteOptions" :key="item.id" :label="item.siteName" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">文章类型：</span>
                <el-select v-model="insertType" style="width: 200px;" placeholder="请选择文章类型" clearable>
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 60px;">生成者：</span>
                <el-select v-model="createUserId" style="width: 200px;" placeholder="请选择生成者" clearable filterable>
                    <el-option v-for="item in creatorOptions" :key="item.id" :label="item.username" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">语言：</span>
                <el-select v-model="langId" style="width: 200px;" placeholder="请选择语言" clearable filterable>
                    <el-option v-for="item in languageOptions" :key="item.id" :label="item.langName" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            </div>
        </div>
        <div class="article-table">
            <el-button type="primary" @click="handleCheck('add')">+ 添加文章</el-button>
            <el-button type="primary" @click="handleOpenTask"><el-icon style="margin-right: 3px;">
                    <DocumentAdd />
                </el-icon>运营文章编排</el-button>
            <el-button type="primary" @click="handleOpenTask1"><el-icon style="margin-right: 3px;">
                    <DocumentAdd />
                </el-icon>投流文章编排</el-button>
            <el-table :data="tableData" v-loading="loading"
                :header-cell-style="{ background: '#fafafa', height: '56px', }"
                style="width: 100%;margin-top: 20px;margin-bottom: 20px; height: calc(100% - 70px);">
                <template v-for="(item, index) in tableHeader" :key="index">
                    <el-table-column :prop="item.prop" :label="item.label" :min-width="item.width" :fixed="index === 0">
                        <template #default="scope">
                            <span style="cursor: pointer" v-if="item.prop === 'id'"
                                @click="handlegoDetail(scope.row)">{{
                                    scope.row[item.prop] }}</span>
                            <div v-else-if="item.prop === 'image' && scope.row[item.prop]"
                                style="width: 120px; height: 100%;">
                                <el-image style="width: 100%; height: 100%" :src="scope.row[item.prop]" :zoom-rate="1.2"
                                    preview-teleported :preview-src-list="[scope.row[item.prop]]" :max-scale="7"
                                    :min-scale="0.2" fit="cover" />
                            </div>
                            <span v-else-if="item.prop === 'status'">{{ StatusMap[scope.row[item.prop]] }}</span>
                            <span v-else-if="item.prop === 'accountId'">{{scope.row?.['accountId'] === -1 ? '其他' :
                                accountNameOptions?.filter((item) => item.id ==
                                    scope.row?.['accountId'])[0]?.name}}</span>
                            <span v-else-if="item.prop === 'langId'">{{languageOptions?.filter((item) => item.id ==
                                scope.row?.['langId'])[0]?.langName || scope.row?.['langId']}}</span>
                            <span v-else-if="item.prop === 'siteId'">
                                <a target="_blank" v-if="scope.row?.['siteId'] !== 4"
                                    style="text-decoration: none;color: #1677ff;"
                                    :href="'https://' + scope.row?.['siteUrl']">{{
                                        scope.row?.['siteUrl'] }}</a>
                                <div v-else style="display: flex;flex-direction: column;">
                                    <span v-for="(item, index) in allSiteOptions?.filter((item) => item.id !==
                                        scope.row?.['siteId'])"> <a target="_blank"
                                            style="text-decoration: none;color: #1677ff;" :href="'https://' + item?.siteUrl
                                                ">{{ item?.siteName }}</a></span>
                                </div>

                            </span>
                            <span v-else>{{ scope.row[item.prop] }}</span>
                        </template>

                    </el-table-column>
                </template>
                <el-table-column label="操作" width="190" fixed="right">
                    <template #default="scope">
                        <div style="display: flex;align-items: center;gap: 15px;flex-wrap: wrap;">
                            <span style="display: flex;align-items: center;">
                                <el-dropdown placement="bottom-start" trigger="click">
                                    <el-icon style="cursor: pointer;color: #1677ff;">
                                        <Postcard />
                                    </el-icon>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <template v-for="(item, index) in tagIdList" :key="index">
                                                <el-dropdown-item @click="() => {
                                                    handleUpdateTag(item.id, scope.row)
                                                }">
                                                    <el-icon style="color: green;"
                                                        v-if="scope.row.tagList?.map((item) => item.id)?.includes(item.id)">
                                                        <CircleCheck />
                                                    </el-icon>
                                                    <div v-else style="width: 18px;"></div>
                                                    {{ item.tagNameEn
                                                    }}
                                                </el-dropdown-item>
                                            </template>

                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </span>
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleCheck('check', scope.row.id)">查看</span>
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleCheck('edit', scope.row.id)">编辑</span>
                            <span style="cursor: pointer;color: red;" @click="handleDelete(scope.row.id)">删除</span>
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleAddCampaign(scope.row.id)">新建Campaign</span>
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleCheckFlow(scope.row.id)">查看跑量</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                style="display: flex;justify-content: end;" layout="total,prev, pager, next,sizes" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <el-drawer v-model="showDrawer" :with-header="false" style="width: 100%;">
            <ArticleDetail @close="() => { showDrawer = false }" :type="type" :id="id" :showDrawer="showDrawer"
                @reSearch="handleSearch" />
        </el-drawer>
        <taskConfiguration ref="taskConfigurationRef" />
        <TaskConfiguration1 ref="taskConfigurationRef1" />
    </div>
</template>

<script setup lang="ts">
import { defineComponent, onActivated, ref } from 'vue';
defineComponent({ name: 'Article' })
import service from '../config';
import ArticleDetail from '../components/articel-detail.vue'
import TaskConfiguration from '../components/taskConfiguration.vue'
import { Search, CircleCheck, DocumentAdd } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import router from '../router';
import TaskConfiguration1 from '../components/taskConfiguration1.vue';
const categoryId = ref('')
const siteId = ref()
const accountId = ref()
const insertType = ref(null)
const createUserId = ref('')
const langId = ref('')
const options = ref([])
const articleId = ref()
const creatorOptions = ref([])
const tableData = ref([])
const showDrawer = ref(false)
const type = ref('')
const id = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref()
const loading = ref(false)
const tagIdList = ref([])
const accountNameOptions = ref([])
const siteOptions = ref([])
const allSiteOptions = ref([])
const taskConfigurationRef = ref(null)
const taskConfigurationRef1 = ref(null)
enum StatusMap {
    通过 = 1,
    驳回,
    审核中,
    已归档,
    新版本审核中,
    新版本驳回
}

const tableHeader = ref([
    { label: '文章ID', prop: 'id', width: 200 },
    { label: '标题', prop: 'title', width: 200 },
    { label: '封面图', prop: 'image', width: 200 },
    { label: '生成者', prop: 'creator', width: 150 },
    { label: '状态', prop: 'status', width: 100 },
    { label: '分类', prop: 'articleCategory', width: 200 },
    { label: '语言', prop: 'langId', width: 120 },
    { label: '账户名称', prop: 'accountId', width: 120 },
    { label: '所属网站', prop: 'siteId', width: 200 },
    { label: '上线时间', prop: 'publishDate', width: 200 },
    { label: '修改时间', prop: 'modified', width: 200 }])

const typeOptions = ref([{ label: '人工', value: 0 }, { label: 'AI运营', value: 1 }, { label: 'AI投流', value: 2 }])

const categoryProps = {
    checkStrictly: true,
}

const getAccount = () => {
    service.get('/account/getAll')
        .then(response => {
            accountNameOptions.value = response?.data
            accountNameOptions.value.push({ id: -1, name: '其他' })
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

const handleSelectAccount = () => {
    const selectedAccountId = accountId.value
    if (selectedAccountId === null || selectedAccountId === undefined) {
        siteOptions.value = [...allSiteOptions.value]
        return
    }
    const filtered = allSiteOptions.value?.filter((item: any) => item.accountId == selectedAccountId) || []
    siteOptions.value = filtered
    const exists = filtered?.some((s: any) => s.id == siteId.value)
    if (!exists) {
        siteId.value = null
    }
}


const buildTree = (nodes, parentId = null) => {
    return nodes
        .filter(node => node.parentId === parentId)
        .map(node => {
            const children = buildTree(nodes, node.value);
            return {
                ...node,
                ...(children.length > 0 ? { children } : {})
            };
        });
}
const getArticleCategory = () => {
    service.get('/article/allCategory')
        .then(response => {
            const treeData = response.data?.map(item => ({
                label: item.name,
                value: item.id,
                parentId: item.parentId,
                alias: item.alias
            }));
            options.value = buildTree(treeData);
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}

const handleSearch = () => {
    loading.value = true
    service.post('/article/page', {
        categoryId: categoryId.value?.[categoryId.value?.length - 1],
        siteId: siteId.value,
        accountId: accountId.value,
        id: Number(articleId.value) || null,
        insertType: insertType.value,
        createUserId: createUserId.value,
        langId: langId.value,
        pageNum: pageNum.value,
        pageSize: pageSize.value
    })
        .then(response => {
            loading.value = false
            tableData.value = response.data?.records
            total.value = response?.data?.total
        })
        .catch(error => {
            loading.value = false
            ElMessage.error(error?.message)
        });
}

const handleCheck = (_type: string, _id?: string) => {
    showDrawer.value = true
    type.value = _type
    id.value = _id || null
}

const handleOpenTask = () => {
    taskConfigurationRef.value.openModal()
}
const handleOpenTask1 = () => {
    taskConfigurationRef1.value.openModal()
}

const handleDelete = (id: string) => {
    service.post('/article/delete', { id })
        .then(response => {
            handleSearch()
            ElMessage.success('删除成功！')
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}

const handleSizeChange = () => {
    pageNum.value = 1
    handleSearch()
}

const handleCurrentChange = () => {
    handleSearch()
}

const getTagAll = () => {
    service.get('/tag/getAll',)
        .then(response => {
            tagIdList.value = response.data
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}


const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            allSiteOptions.value = response?.data || []
            siteOptions.value = [...allSiteOptions.value]
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}

const getCreatorList = () => {
    service.get('/user/getAll')
        .then(response => {
            creatorOptions.value = response?.data || []
        })
        .catch(error => {
            ElMessage.error(error || error?.message)
        });
}


const handleUpdateTag = (tagId, row) => {
    service.post('/article/updateTag', {
        op: row?.tagList?.map((item) => item.id)?.includes(tagId) ? 0 : 1,
        articleId: row?.id,
        tagId: tagId
    })
        .then(response => {
            handleSearch()
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

const handleAddCampaign = (id) => {
    router.push({
        name: 'Campaign',
        query: { articleId: id }
    })
}

const handleCheckFlow = (id) => {
    router.push({
        name: 'Flow',
        query: { articleId: id }
    })
}

const handlegoDetail = (row) => {
    window.open(`${'https://' + row?.['siteUrl']}/detail/${row.id}`, '_blank')
}

const languageOptions = ref([])
const getlangCategory = () => {
    service.get('/lang/getAll')
        .then(response => {
            languageOptions.value = response?.data
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}

onActivated(() => {
    getlangCategory()
    getTagAll()
    getArticleCategory()
    getAccount()
    getCreatorList()
    handleSearch()
    getSite()
})
</script>

<style lang="scss">
.el-dropdown__popper .el-dropdown-menu {
    max-height: 450px;
}

.article-page {
    background-color: #fff;
    height: calc(100% - 10px);
    padding: 30px;
    width: 100%;
    box-sizing: border-box;

    .article-title {
        font-size: 20px;
        font-weight: 600;
    }

    .fliter {
        display: flex;
        align-items: center;
        margin: 30px 0;
        flex-wrap: wrap;
        gap: 10px 12px;
        /* 行列间距 */

        .filter-item {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
    }

    .el-button--primary {
        background-color: #1677ff;
    }

    .article-table {
        margin-top: 20px;
        height: calc(100% - 180px);
    }

    .el-drawer {
        width: 100% !important;
    }

    .el-drawer__body {
        padding: 0;
    }

    .el-table__row {
        font-size: 13px;
    }

}
</style>
